package com.shexianyu.medium;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shexianyu
 * @desc 794. 有效的井字游戏
 * board.length == 3
 * board[i].length == 3
 * board[i][j] 为 'X'、'O' 或 ' '
 * @date 2021/12/9
 */
public class ValidTicTacToe {
    /**
     * 待完善，不准确
     *
     * @param board
     * @return
     */
    public boolean validTicTacToe(String[] board) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length(); j++) {
                //System.out.print(board[i].charAt(j) + "\t");
                map.put(board[i].charAt(j), map.getOrDefault(board[i].charAt(j), 0) + 1);
            }
            //System.out.println();
        }
        System.out.println("X:" + map.get('X'));
        System.out.println("空格:" + map.get(' '));
        System.out.println("O:" + map.get('O'));
//        if (map.get('X') == 0 && map.get('O') >= 1) {
//            return false;
//        } else if ((map.get('X') - map.get('O')) >= 2) {
//            return false;
//        } else if (map.get('X') == 3 && map.get('O') == 3) {
//
//        }
        if (map.get('O') != map.get('X') && map.get('O') != map.get('X') - 1) {
            return false;
        }
        if (win(board, 'X') && map.get('O') != map.get('X') - 1) {
            return false;
        }
        if (win(board, 'O') && map.get('O') != map.get('X')) {
            return false;
        }
        return true;
    }


    /**
     * 官方题解
     *
     * @param board
     * @return
     */
    public boolean validTicTacToe1(String[] board) {
        int xCount = 0, oCount = 0;
        for (String row : board) {
            for (char c : row.toCharArray()) {
                xCount = (c == 'X') ? (xCount + 1) : xCount;
                oCount = (c == 'O') ? (oCount + 1) : oCount;
            }
        }
        if (oCount != xCount && oCount != xCount - 1) {
            return false;
        }
        if (win(board, 'X') && oCount != xCount - 1) {
            return false;
        }
        if (win(board, 'O') && oCount != xCount) {
            return false;
        }
        return true;
    }

    public boolean win(String[] board, char p) {
        for (int i = 0; i < 3; ++i) {
            if (p == board[0].charAt(i) && p == board[1].charAt(i) && p == board[2].charAt(i)) {
                return true;
            }
            if (p == board[i].charAt(0) && p == board[i].charAt(1) && p == board[i].charAt(2)) {
                return true;
            }
        }
        if (p == board[0].charAt(0) && p == board[1].charAt(1) && p == board[2].charAt(2)) {
            return true;
        }
        if (p == board[0].charAt(2) && p == board[1].charAt(1) && p == board[2].charAt(0)) {
            return true;
        }
        return false;
    }
}
